package com.sgb.kjwl.view.ui.activity.enterprise;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.capital.view.widget.DecimalInputTextWatcherMore;
import com.sgb.capital.view.widget.NoSymbolputNewFilter;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityServiceTypeBinding;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.enterprise.SecerTitleEntity;
import com.sgb.kjwl.model.entity.enterprise.ServiceListEntiy;
import com.sgb.kjwl.service.CodeTimerService;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.EditTextUtils;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.utils.PickerHelper;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.enterprise.ServiceListAdpater;
import com.swgk.core.view.weiget.CountMenuView;
import com.sgb.kjwl.viewmodel.enterprise.ServiceTypeModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author 陈方凯
 */
public class ServiceTypeActivity extends AppActivity implements View.OnClickListener {

    private ServiceTypeModel mViewModel;
    private ActivityServiceTypeBinding mBinding;
    private ServiceListAdpater mListAdapter;
    private LinearLayoutManager mListLayoutManger;

    private Intent intentService;
    private boolean isLogin;
    private String phone;
    boolean getCode = false;
    OptionsPickerView<IpPickSelectEntity> choice_type_options;
    TimePickerView timePickerView;
    long mEndTime = 0;
    int demandType = -1;


    public static void start(Context mContext, String id, String title) {
        Intent mIntent = new Intent();
        mIntent.setClass(mContext, ServiceTypeActivity.class);
        mIntent.putExtra("data", id);
        mIntent.putExtra("title", title);
        mContext.startActivity(mIntent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mUpdateReceiver, updateIntentFilter());
    }

    @Override
    protected void initView() {
        super.initView();

        mViewModel = new ViewModelProvider(this).get(ServiceTypeModel.class);
        mViewModel.setMitemid(getIntent().getStringExtra("data"));
        mViewModel.titlename = getIntent().getStringExtra("title");
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_service_type);
        mBinding.setVariable(BR.needmodel, mViewModel);
        mBinding.setLifecycleOwner(this);
        mBinding.actionBar.setTitle(mViewModel.titlename);
        mBinding.include.etPrice.addTextChangedListener(new DecimalInputTextWatcherMore(mBinding.include.etPrice, 10, 2));
        mBinding.include.etTitle.setFilters(new InputFilter[]{new NoSymbolputNewFilter()});
        mBinding.include.etUsername.setFilters(new InputFilter[]{new NoSymbolputNewFilter()});
        EditTextUtils.setEditTextFlag(mBinding.include.etTitle,null,20);
        EditTextUtils.setEditTextFlag(mBinding.include.etUsername,null,10);
        EditTextUtils.setEditTextFlag(mBinding.include.etDanwei, null, 20);
        mBinding.include.imageDelete.setOnClickListener(this);
        mViewModel.setCheckData();
        initRecyclerView();
        initObserver();
        initListener();
        initLoginData();
        mViewModel.getServerTitleLable();
        mViewModel.getServiceList();
    }

    private void initLoginData() {
        //是否登录
        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            isLogin = true;
            mBinding.include.etPhone.setText(
                    mViewModel.settingPhone(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""))
            );
            mBinding.include.tvCodeGet.setClickable(true);
            mBinding.include.tvCodeGet.setTextColor(Color.parseColor("#5792FD"));
            mBinding.include.etPhone.setFocusable(false);
//            mBinding.include.llCode.setVisibility(View.VISIBLE);
        }else{
            mBinding.include.tvCodeGet.setClickable(false);
            mBinding.include.tvCodeGet.setTextColor(Color.parseColor("#885792FD"));
        }
    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {

        mListAdapter = new ServiceListAdpater(getActivity(), new ArrayList<>());
        mListLayoutManger = new LinearLayoutManager(getActivity());
        mBinding.recyclerViewBottom.setLayoutManager(mListLayoutManger);
        mBinding.recyclerViewBottom.setAdapter(mListAdapter);
    }


    /**
     * 数据响应
     */
    private void initObserver() {
        //二级分裂列表
        mViewModel.secondLevelData.observe(this, list -> {
            mBinding.calendarMenuView.initData(ServiceTypeActivity.this.getSupportFragmentManager(), list, new CountMenuView.OnItemClick() {
                @Override
                public void onItemClick(MenuEntity entity, int position, int num) {
                    SecerTitleEntity mentity = new SecerTitleEntity();
                    mentity.setCategoryFirstId(Long.parseLong(mViewModel.mitemid));
                    mentity.setCategoryFirstName(mViewModel.titlename);
                    mentity.setCategorySecondId(Long.parseLong(entity.getId()));
                    if(entity.getLev()==3){
                        mentity.setCategorySecondId(entity.getParentNo());
                        mentity.setCategoryThirdId(Long.parseLong(entity.getId()));
                    }
                    ProfessionalQuoteActivity.start(getActivity(), mentity);
                }
            });
        });
        //底部列表
        mViewModel.list_data.observe(this, list -> {
            if (list.size() > 0) {
                mListAdapter.setDatas(list);
                mBinding.tvLookmore.setVisibility(View.VISIBLE);
            } else {
                mBinding.layoutNull.setVisibility(View.VISIBLE);
                mBinding.recyclerViewBottom.removeAllViews();
                mBinding.tvLookmore.setVisibility(View.GONE);
            }
        });
        //验证码
        mViewModel.VerificationCode.observe(this, s -> MToast.showToast(ServiceTypeActivity.this, s));

        //服务发布
        mViewModel.publishDemand.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                switch (s) {
                    case "操作成功":
                        mBinding.include.etTitle.setText("");
                        mBinding.include.etCode.setText("");
                        mBinding.include.etNeedChoice.setText("");
                        mBinding.include.etPrice.setText("");
                        mBinding.include.textTime.setText("");
                        mBinding.include.etUsername.setText("");
                        mBinding.include.etDanwei.setText("");
                        mBinding.include.tvCodeGet.setText("获取验证码");
//                        mBinding.include.llCode.setVisibility(isLogin ? View.VISIBLE : View.GONE);
                        getCode = false;
                        mEndTime = 0;
                        mBinding.include.textTime.setText("");
                        mBinding.include.imageDelete.setImageResource(R.mipmap.icon_expand);
                        MToast.showToast(getActivity(), "您的需求已提交，正在为您匹配服务商！");
                        if (!isLogin) {
                            VerificationCodeLoginActivity.start(getActivity());
                            mBinding.include.etPhone.setText("");
                        }
                        break;
                    default:
                        MToast.showToast(getActivity(), s);
                }
            }
        });
        mViewModel.list_data.observe(this, list -> {
            if (list.size() > 0) {
                mListAdapter.setDatas(list);
            } else {
                mBinding.layoutNull.setVisibility(View.VISIBLE);
            }
        });
        mViewModel.show_toast.observe(this, data -> {
            MToast.showToast(getActivity(), data);
        });

        mViewModel.ShowLoading.observe(this, type -> {
            switch (type) {
                case 1:
                    com.swgk.core.dialog.DialogHelper.showProgressDialog(getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelper.dismissProgressDialog();
                    break;
            }
        });
    }


    /**
     * 初始化Listener
     */
    private void initListener() {


        mBinding.tvLookmore.setOnClickListener(view -> {
            SecerTitleEntity entity = new SecerTitleEntity();
            entity.setCategoryFirstId(Long.parseLong(mViewModel.mitemid));
            entity.setCategoryFirstName(mViewModel.titlename);
            entity.setCategorySecondId(0);
            entity.setCategorySecondName("");
            ProfessionalQuoteActivity.start(getActivity(), entity);
        });


        mBinding.include.etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!isLogin)
                    if (!CheckUtils.isMobileNum_new(mBinding.include.etPhone.getText().toString().trim())) {
                        mBinding.include.tvCodeGet.setClickable(false);
                        mBinding.include.tvCodeGet.setTextColor(Color.parseColor("#885792FD"));
                    } else {
                        mBinding.include.tvCodeGet.setClickable(true);
                        mBinding.include.tvCodeGet.setTextColor(Color.parseColor("#5792FD"));
                    }
            }
        });

        mListAdapter.setOnItemClick(new AdapterOnItemClick<ServiceListEntiy>() {
            @Override
            public void onItemClick(ServiceListEntiy serviceListEntiy, int position) {
                if (position != -1) {//点击详情
                    WebsiteInfoActivity.start(getActivity(), serviceListEntiy.getNo(), serviceListEntiy.getPromulgatorType() == 1 ? WebsiteInfoActivity.WEBSITE_FOR_COMPANY : WebsiteInfoActivity.WEBSITE_FOR_TEAM);
                } else {//点击关注
                    if (!ClickUtils.isDoubleClick()) {
                        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                            VerificationCodeLoginActivity.start(ServiceTypeActivity.this);
                            return;
                        }


                        if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                            com.sgb.kjwl.utils.DialogHelper.showDialog(getActivity(), "温馨提示", "请先完成实名认证", "去认证", new DialogFunction() {
                                @Override
                                public void normalRoundDialog() {
                                    CertificationActivity.start(getActivity(), "1");
                                }
                            });
                            return;
                        }

                        if (UserOperating.getInstance().isCompany()) {
                            MToast.showLongToast(getActivity(), "功能正在优化中！");
                        }

                        mViewModel.setFollow(serviceListEntiy.getNo(), serviceListEntiy.getPromulgatorType());
                    }
                }
            }
        });
        mBinding.include.tvCodeGet.setOnClickListener(this);
        mBinding.include.tvSubmit.setOnClickListener(this);
        mBinding.include.linChoiceType.setOnClickListener(this);
        mBinding.include.etNeedChoice.setOnClickListener(this);
        mBinding.include.linChoicetime.setOnClickListener(this);
        mBinding.include.textTime.setOnClickListener(this);
    }

    /**
     * 防重点击事件
     *
     * @param v
     */
    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        switch (v.getId()) {
            case R.id.tv_code_get:
                if(!getCode){
                    getCode = true;
                }
                intentService = new Intent(ServiceTypeActivity.this, CodeTimerService.class);
                startService(intentService);
                setPhone();
                mViewModel.getVerificationCode(phone);
                break;
            case R.id.tv_submit:
                if (TextUtils.isEmpty(mBinding.include.etTitle.getText().toString().trim())) {
                    MToast.showToast(getActivity(), "请输入需求名称");
                    return;
                }

                if (TextUtils.isEmpty(mBinding.include.etNeedChoice.getText().toString().trim())) {
                    MToast.showToast(getActivity(), "请选择需求分类");
                    return;
                }
//                if (TextUtils.isEmpty(mBinding.include.etPrice.getText().toString().trim())) {
//                    MToast.showToast(getActivity(), "请输入预算价格！");
//                    return;
//                }
//                if (TextUtils.isEmpty(mBinding.include.textTime.getText().toString().trim())) {
//                    MToast.showToast(getActivity(), "请选择需求最后办理期限！");
//                    return;
//                }

                if (TextUtils.isEmpty(mBinding.include.etUsername.getText().toString().trim())) {
                    MToast.showToast(getActivity(), "请输入联系人姓名");
                    return;
                }


                if (!isLogin && TextUtils.isEmpty(mBinding.include.etPhone.getText().toString().trim())) {
                    MToast.showToast(getActivity(), "请输入手机号");
                    return;
                }
                if (!isLogin && !CheckUtils.isMobileNum_new(mBinding.include.etPhone.getText().toString().trim())) {
                    MToast.showToast(getActivity(), "请输入正确的电话格式");
                    return;
                }
//                if (TextUtils.isEmpty(mBinding.include.etCode.getText().toString().trim())) {
//                    MToast.showToast(getActivity(), "请输入验证码");
//                    return;
//                }
                setPhone();
                mViewModel.publishDemandFun(
                        mBinding.include.etTitle.getText().toString().trim()
                        , demandType
                        , TextUtils.isEmpty(mBinding.include.etPrice.getText().toString().trim())?"":mBinding.include.etPrice.getText().toString().trim()
                        , mEndTime
                        , mBinding.include.etUsername.getText().toString().trim()
                        , phone
                        , mBinding.include.etCode.getText().toString().trim(),
                        mBinding.include.etDanwei.getText().toString().trim());
                break;
            case R.id.et_need_choice:
            case R.id.lin_choice_type:
                KeyboardUtils.hideSoftInput(this);
                if (choice_type_options == null) {
                    choice_type_options = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, view) -> {
                        mBinding.include.etNeedChoice.setText(mViewModel.getTypeData().get(options1).getName());
                        demandType = Integer.parseInt(mViewModel.getTypeData().get(options1).getId());
                    }).setCancelText("取消").setSubCalSize(15)
                            .setCancelColor(Color.parseColor("#666666"))
                            .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                            .setSubmitText("确定")
                            .setSubmitColor(Color.parseColor("#5792FD"))
                            .setTextColorCenter(Color.parseColor("#ff333333"))
                            .setContentTextSize(15)
                            .setTitleText("选择分类")
                            .setLineSpacingMultiplier(2.5f)
                            .setDividerColor(Color.parseColor("#EDEDED"))
                            .build();
                    choice_type_options.setPicker(mViewModel.getTypeData());
                    choice_type_options.setSelectOptions(0);

                }
                choice_type_options.show();
                break;

            case R.id.lin_choicetime:
            case R.id.text_time:
                showChoiceTimeDialog();
                break;
            case R.id.image_delete:
                if(mEndTime>0){
                    mEndTime = 0;
                    mBinding.include.textTime.setText("");
                    mBinding.include.imageDelete.setImageResource(R.mipmap.icon_expand);
                }else{
                    showChoiceTimeDialog();
                }

                break;
        }
    }

    private void showChoiceTimeDialog(){
        KeyboardUtils.hideSoftInput(this);
        if (timePickerView == null) {
            Calendar startDate = Calendar.getInstance();
            Calendar endDate = new GregorianCalendar();
            endDate.setTime(new Date(new BigDecimal(startDate.getTime().getTime()).add(new BigDecimal(31536000000L * 5)).add(new BigDecimal(86400000)).longValue()));
            timePickerView = PickerHelper.with(this).getCommonTimeBuild("", new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {

                    mEndTime = date.getTime();
                    mBinding.include.textTime.setText(DateUtils.timestampToDate(date.getTime()));
                    mBinding.include.imageDelete.setImageResource(R.mipmap.search_close);
                }
            }).setRangDate(startDate, endDate).setCancelText("取消").setSubCalSize(15)
                    .setCancelColor(Color.parseColor("#666666"))
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                    .setSubmitText("确定")
                    .setSubmitColor(Color.parseColor("#5792FD"))
                    .setTextColorCenter(Color.parseColor("#ff333333"))
                    .setContentTextSize(15)
                    .setTitleText("选择需求最后办理期限")
                    .setLineSpacingMultiplier(2.5f)
                    .setDividerColor(Color.parseColor("#EDEDED"))
                    .build();
        }
        timePickerView.show();
    }

    private void setPhone() {
        if (!isLogin) {
            phone = mBinding.include.etPhone.getText().toString();
        } else {
            phone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        }
    }

    // 注册广播
    private static IntentFilter updateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CodeTimerService.IN_RUNNING);
        intentFilter.addAction(CodeTimerService.END_RUNNING);
        return intentFilter;
    }

    // 广播接收者
    private final BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action) {
                case CodeTimerService.IN_RUNNING:
                    if (mBinding.include.tvCodeGet.isEnabled())
                        mBinding.include.tvCodeGet.setEnabled(false);
                    // 正在倒计时
//                    mBinding.include.tvCodeGet.setTextColor(Color.GRAY);
                    mBinding.include.tvCodeGet.setText(intent.getStringExtra("time") + "秒后重新发送");

                    break;
                case CodeTimerService.END_RUNNING:
                    // 完成倒计时
//                    mBinding.include.tvCodeGet.setTextColor(getResources().getColor(R.color.new_blue));
                    mBinding.include.tvCodeGet.setEnabled(true);
                    mBinding.include.tvCodeGet.setText(getCode?"重新获取验证码":"获取验证码");
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }
}
